# -*- coding: utf-8 -*-
from django.http import HttpResponseRedirect, HttpResponse
from django.shortcuts import render_to_response
from django.utils import simplejson
from collectionsapp.models import Collection
from collectionsapp.forms import CollectionForm
from categoriesapp.forms import CategoryForm
from categoriesapp.models import Category
from uidpapp.models import UIDP, UIDPImageExample, ImageExample, UIDPImplementationExample, UIDPSolutions, Relationship, Problem, ProblemContext
from uidpapp.forms import UIDPForm

def list_patterns_json(request, collection_id):
    collection = Collection.objects.get(pk=collection_id);
    uidps = UIDP.objects.filter(collections=collection).order_by("name")
    
    #return HttpResponse(simplejson.dumps(dict(collections.values_list('id', 'name'))), mimetype="application/json")
    return HttpResponse(simplejson.dumps(dict(uidps.values_list('id','name'))), mimetype="application/json")

def list_collections(request):
    collections = Collection.objects.all().order_by("id")
    collection_id = 0
    return render_to_response('home.html', locals())

def list_patterns(request, collection_id):
    info = get_collections_uidps(collection_id)
    categories = Category.objects.all().order_by("name")
    collections = Collection.objects.all()
    collection = Collection.objects.get(pk=collection_id);
    collection_id = collection.id
    uidps = ProblemContext.objects.all()#UIDP.objects.filter(collections=collection).order_by("name")
    
    category_id = 0
    
    return render_to_response('uidps_list.html', locals())
    
def create_collection(request):
    if request.method == 'POST':
        form = CollectionForm(request.POST)
        if form.is_valid():
            cd = form.cleaned_data
            collection = form.save(cd)

            return HttpResponseRedirect('/collections/%d' % collection.id)
    else:
        title = "Nova coleção"
        description = "Insira abaixo as informações básicas sobre a nova coleção."
        collections = Collection.objects.all()
        collection_id = 0
        form = CollectionForm()
        
    return render_to_response('new_collection.html', locals())

def add_category_to_collection(request, collection_id):
    if request.method == 'POST':
        form = CategoryForm(request.POST)
        if form.is_valid():
            cd = form.cleaned_data
            category = form.save(cd)
            
            return HttpResponseRedirect('/')
    else:
        title = "Nova categoria"
        description = "Insira abaixo as informações básicas sobre a nova categoria."
        form = CategoryForm()
        
    return render_to_response('new_category.html', locals())

# Lists all uidps for the user.
def add_uidps_to_collection(request, collection_id):
    collection = Collection.objects.get(pk=collection_id)
    collection_id = collection.id
    collections = Collection.objects.all()
    
    # Collection's uidps
    collection_uidps = UIDP.objects.filter(collections=collection)
    uidps = ProblemContext.objects.filter(UIDP__in=collection_uidps)
    
    # Remaining uidps
    others_uidps = UIDP.objects.exclude(collections=collection)
    
    return render_to_response('collection_uidps.html', locals())

# Adds a selected uidp to the collection list.
def add_uidp_to_collection(request, collection_id, uidp_id):
    UIDP.objects.get(pk=uidp_id).collections.add(Collection.objects.get(pk=collection_id))

    return add_uidps_to_collection(request, collection_id)

def select_uidps_from_collection(request, collection_id):
    collections = Collection.objects.all()
    collection = Collection.objects.get(pk=collection_id)
    
    actions = Problem.objects.distinct("action").order_by("action")
    
    return render_to_response('select_uidp.html', locals());
    
def select_uidps_from_collection_with_action(request, collection_id, action_id):
    collections = Collection.objects.all()
    collection = Collection.objects.get(pk=collection_id)
    
    actions = Problem.objects.distinct("action").order_by("action")
    
    problem_action = Problem.objects.get(pk=action_id)
    objects = Problem.objects.filter(action=problem_action.action).distinct("object").order_by("object")
    
    return render_to_response('select_uidp.html', locals());
    
def select_uidps_from_collection_with_object(request, collection_id, action_id, object_id):
    collections = Collection.objects.all()
    collection = Collection.objects.get(pk=collection_id)
    
    actions = Problem.objects.distinct("action")
    problem_action = Problem.objects.get(pk=action_id)
    
    objects = Problem.objects.filter(action=problem_action.action).distinct("object").order_by("object")
    problem_object = Problem.objects.get(pk=object_id)
    
    filtered_problems = Problem.objects.filter(action=problem_action.action).filter(object=problem_object.object)

    complements = []
    for i in filtered_problems:
        complements.append(i.complement)    
    
    if not complements or len(complements) == 1:
        uidps = ProblemContext.objects.filter(problem__in=filtered_problems)
        print uidps
    
    return render_to_response('select_uidp.html', locals());

def select_uidps_from_collection_with_complement(request, collection_id, action_id, object_id, complement_id):
    collections = Collection.objects.all()
    collection = Collection.objects.get(pk=collection_id)
    
    problem_action = Problem.objects.get(pk=action_id)
    problem_object = Problem.objects.get(pk=object_id)
    problem_complement = Problem.objects.get(pk=complement_id)
    
    filtered_problems = Problem.objects.filter(action=problem_action.action).filter(object=problem_object.object).filter(complement=problem_complement.complement)

    uidps = ProblemContext.objects.filter(problem__in=filtered_problems)
    print uidps
    
    return render_to_response('select_uidp.html', locals());

    
def remove_uidp_from_collection(request, collection_id, uidp_id):
    UIDP.objects.get(pk=uidp_id).collections.remove(Collection.objects.get(pk=collection_id))

    return HttpResponseRedirect('/collections/%d/uidps/add' % int(collection_id))

def create_uidp_and_add_to_collection(request, collection_id):
    if request.method == 'POST':
        form = UIDPForm(request.POST)
        if form.is_valid():
            print form.is_valid
            cd = form.cleaned_data
            uidp = form.save(cd)
            
            # Add uidp to collection
            collection = Collection.objects.get(pk=collection_id)
            uidp.collections.add(collection)
            
            for i in request.POST.getlist('category'):
                uidp.categories.add(Category.objects.get(pk=i))

            return HttpResponseRedirect('/collections/%d' % collection.id)
    else:
        collections = Collection.objects.all()
        collection_id = int(collection_id)
        categories = Category.objects.all().order_by("name")
        form = UIDPForm()
        
    return render_to_response('new_uidp.html', locals())

def display_collection_uidp(request, collection_id, uidp_id):
    info = get_collections_uidps(collection_id)
    info["collection"] = Collection.objects.get(pk=collection_id)
    info["uidp"] = UIDP.objects.filter(collections=info["collection"]).get(pk=uidp_id)
    info["categories"] = Category.objects.filter(uidp=info['uidp']).order_by("name")
    uidp_images = UIDPImageExample.objects.filter(uidp=info["uidp"])
    info["images"] = ImageExample.objects.filter(image__id__in=uidp_images).filter(collection=info["collection"])
    info["references"] = info["images"].distinct('parent_name')
    info["examples"] = UIDPImplementationExample.objects.filter(uidp=info["uidp"]).filter(collection=info["collection_id"]).order_by("id")
    info["solutions"] = UIDPSolutions.objects.filter(uidp=info["uidp"]).filter(collection=info["collection_id"])
    info["relationships"] = Relationship.objects.filter(source=info["uidp"]).filter(collection=info["collection_id"])
    info["relationships_as_target"] = Relationship.objects.filter(target=info["uidp"]).filter(collection=info["collection_id"])
    info["other_collections"] = Collection.objects.filter(uidp=info["uidp"]).exclude(pk=collection_id)
    
    return render_to_response('uidp.html', info)

def edit_collection_uidp(request, collection_id, uidp_id):
    collections = Collection.objects.all()
    collection = Collection.objects.get(pk=collection_id)
    collection_id = int(collection_id)
    action = "edit"
    categories = Category.objects.all().order_by("name")
    uidp = UIDP.objects.get(pk=uidp_id)
    selected_categories = Category.objects.filter(uidp=uidp)
    
    if request.method == 'POST':
        form = UIDPForm(request.POST)
        
        if form.is_valid():
            cd = form.cleaned_data
            form.save(cd)
            #uidp.name = cd["name"]
            #uidp.context = cd["context"]
            #uidp.save()
            
            for category in selected_categories:
                uidp.categories.remove(category)
                
            for i in request.POST.getlist('category'):
                uidp.categories.add(Category.objects.get(pk=i))
                
            
            return HttpResponseRedirect('/collections/%d' % collection_id)
    
    form = UIDPForm()

    return render_to_response('new_uidp.html', locals())

def get_collections_uidps(collection_id):
    collections = Collection.objects.all()
    collection = Collection.objects.get(pk=collection_id)
    collection_id = collection.id
    uidps = UIDP.objects.filter(collections=collection)

    d = {}
    d["collections"] = collections
    d["collection"] = collection
    d["collection_id"] = collection_id
    d["collection_uidp"] = uidps
    
    return d